import md5 from 'md5';
import translate from './translate';
import language from '../file/language';
import languageList from '../file/languageList';
import superagent from 'superagent';
const appid = '20191019000342769';
const password = 'fjPQEXaQ6eV10bWbvaaD';
class baidu implements translate {
  async trans(lan: language, value: string): Promise<string> {
    let q = value;
    let from = this.getFormTo(lan.getRawLanguage());
    let to = this.getFormTo(lan.getNewLanguage());
    let salt = new Date().getTime();
    let v1 = appid + q + salt + password;
    let v2 = md5(v1);
    let url = `/api/translate/baidu`;
    let data;
    await superagent
      .post(url)
      .send({
        q: q,
        from: from,
        to: to,
        appid: appid,
        salt: salt,
        sign: v2
      })
      .set('Access-Control-Allow-Origin', '*')
      .set('Content-Type', 'application/x-www-form-urlencoded')
      .then(v => {
        data = v;
      });
    return JSON.parse(data.text).trans_result[0].dst;
  }
  private getFormTo(language: languageList): string {
    switch (language) {
      case languageList['Chinese-s']: {
        return 'zh';
      }
      case languageList['Chinese-t']: {
        return 'zh';
      }
      case languageList['France']: {
        return 'fra';
      }
      case languageList['German']: {
        return 'de';
      }
      case languageList['English']: {
        return 'en';
      }
    }
  }
}

let trans = new baidu();

export default trans;
